package com.gmlive.common.imageloader.request

import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.widget.ImageView
import com.facebook.drawee.view.SimpleDraweeView
import com.gmlive.common.imageloader.ImageLoader
import com.gmlive.common.imageloader.dip2px
import com.gmlive.common.imageloader.fresco.IkFresco

/**
 *  Create by: fanfeiyue
 *  on: 2019-11-20
 *  desc:
 */
class RequestCreate(uri: Uri) {

    private val data = Request(uri)

    fun circle(): RequestCreate {
        data.circled = true
        return this
    }

    fun resize(width: Int, height: Int): RequestCreate {
        data.sizeOption = SizeOption(width, height)
        return this
    }

    fun resizeByDp(width: Int, height: Int): RequestCreate {
        data.sizeOption = SizeOption(width.dip2px(), height.dip2px())
        return this
    }

    fun centerCrop(): RequestCreate {
        data.centerCrop = true
        return this
    }

    fun placeHolder(resId: Int?): RequestCreate {
        return placeHolder(getDrawable(resId))
    }

    fun placeHolder(drawable: Drawable?): RequestCreate {
        data.placeHolderDrawable = drawable
        return this
    }

    fun error(resId: Int?): RequestCreate {
        return error(getDrawable(resId))
    }

    fun error(drawable: Drawable?): RequestCreate {
        data.errorDrawable = drawable
        return this
    }

    fun autoPlay(autoPlay: Boolean?):RequestCreate{
        data.autoPlay = autoPlay
        return this
    }

    fun into(view: ImageView) {
        IkFresco.intoImage(view, data)
    }

    fun into(view: SimpleDraweeView) {
        IkFresco.intoImage(view, data)
    }

    fun getBitmap(picId: Int, bitmapLoadListener: ((picId: Int, bitmap: Bitmap?) -> Unit)?) {
        IkFresco.getBitmap(picId, data, bitmapLoadListener)
    }

    private fun getDrawable(resId: Int?): Drawable? {
        return resId?.let {
            when {
                Build.VERSION.SDK_INT >= 21 -> ImageLoader.app.getDrawable(resId)
                Build.VERSION.SDK_INT >= 19 -> ImageLoader.app.resources.getDrawable(resId)
                else -> null
            }
        }
    }

}

class SizeOption(var width: Int, var height: Int)

